package logic

import (
	"context"
	"errors"
	"math/rand"
	"novel-mgr1/cache"
	"time"

	"novel-mgr1/userrpc/internal/svc"
	"novel-mgr1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SandLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SandLogic {
	return &SandLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SandLogic) Sand(in *userrpc.SandRequest) (*userrpc.SandResponse, error) {
	// todo: add your logic here and delete this line
	i, _ := cache.Rdb.Get(l.ctx, "smsNumber"+in.Mobile).Int()
	if i >= 1 {
		return nil, errors.New("一分钟之内只能发送一次")
	}
	code := rand.Intn(9000) + 1000
	//sand, err := pkg.Sand(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if sand.Code != 2 {
	//	return nil, errors.New("发送失败")
	//}
	cache.Rdb.Set(l.ctx, "sms"+in.Mobile, code, time.Minute*1)
	result, _ := cache.Rdb.Incr(l.ctx, "smsNumber"+in.Mobile).Result()
	if result == 1 {
		cache.Rdb.Expire(l.ctx, "smsNumber"+in.Mobile, time.Minute*1)
	}
	return &userrpc.SandResponse{}, nil
}
